package com.lysj.merchant.management.feignImpl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lysj.admin.common.merchant.feign.MerchantServiceFeign;
import com.lysj.admin.common.result.domain.AuthenticationResult;
import com.lysj.admin.utils.web.ParamUtil;
import com.lysj.merchant.management.AuthConstant;
import com.lysj.merchant.management.domain.Permission;
import com.lysj.merchant.management.domain.User;
import com.lysj.merchant.management.service.PermissionService;
import com.lysj.merchant.management.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author Created by wtl on 2019-03-14 10:13
 * @description
 */
@RestController
public class MerchantServiceFeignImpl implements MerchantServiceFeign {

    @Resource
    private PermissionService permissionService;
    @Resource
    private UserService userService;
    @Value("${secret.key}")
    private String key;
    @Value("${secret.tokenExpiration}")
    private int tokenExpiration;
    @Value("${secret.tokenRefresh}")
    private int tokenRefresh;

    @Override
    public AuthenticationResult authentication(String token, String path) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC512(key)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return new AuthenticationResult("token错误",AuthenticationResult.ResultStatus.TOKEN_ERROR);
        }
        String iss = jwt.getIssuer();
        String userId = jwt.getSubject();
        if (ParamUtil.isBlank(userId) || ParamUtil.isBlank(iss) || !AuthConstant.AUTH_NAME.equals(iss)) {
            return new AuthenticationResult("token错误",AuthenticationResult.ResultStatus.TOKEN_ERROR);
        }
        // 如果是商户或者店长登录，拥有全部权限
        User user = userService.findOne(userId);
        //获取用户权限树
        List<Permission> permissions = permissionService.findByUserIdAndType(userId);

        if (user.getUserType() == 3) {

            if (ParamUtil.isBlank(permissions)) {
                return new AuthenticationResult("权限不足",AuthenticationResult.ResultStatus.NO_ACCESS);
            }
            //匹配路径是否符合用户权限
            boolean isAccess = false;
            for (Permission permission : permissions) {
                if (permission.getPath().equals(path)) {
                    isAccess = true;
                    break;
                }
            }
            if (!isAccess) {
                return new AuthenticationResult("权限不足",AuthenticationResult.ResultStatus.NO_ACCESS);
            }
        }
        //判断用户token是否需要刷新
        Date expires = jwt.getExpiresAt();
        Date now = new Date();
        if ((now.getTime() - expires.getTime()) < tokenRefresh * 60 * 1000) {
            token = JWT.create().withIssuer(AuthConstant.AUTH_NAME).withSubject(userId)
                    .withExpiresAt(new Date(now.getTime() + tokenExpiration * 60 * 1000))
                    .sign(Algorithm.HMAC512(key));
        }
        return new AuthenticationResult(token,AuthenticationResult.ResultStatus.SUCCESS);
    }
}
